package com.pym.bs.controller;

import com.pym.bs.dao.RolePermissionMapper;
import com.pym.bs.dao.UserMapper;
import com.pym.bs.domain.RolePermission;
import com.pym.bs.domain.User;
import com.pym.bs.dto.UserDTO;
import com.pym.bs.service.UserService;
import com.pym.bs.utils.Pageable;
import com.pym.bs.utils.ResultVOUtils;
import com.pym.bs.utils.UserDetailsUtils;
import com.pym.bs.vo.PageVO;
import com.pym.bs.vo.ResultVO;
import com.pym.bs.vo.UserDetailsVO;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping(value = "api/user")
public class UserController {

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserService userService;

    @Resource
    private RolePermissionMapper rolePermissionMapper;

    @RequestMapping(value = "/info")
    @ResponseBody
    public ResultVO info() {
        UserDetailsVO userDTO = new UserDetailsVO();
        UserDTO user= UserDetailsUtils.getUserDetailsDTO().getUser();
        User newUser = userMapper.selectByPrimaryKey(user.getId());
        BeanUtils.copyProperties(newUser, userDTO);
        List<String> roles = new ArrayList<>();
//        roles.add("admin");
//        List<RolePermission> permissionList = rolePermissionMapper.selectByUserId(user.getId());
//        System.out.println(permissionList);
//        if(permissionList!=null&&permissionList.size()>0){
//            for(RolePermission rolePermission:permissionList){
//                roles.add(rolePermission.getPermissionContent());
//            }}else {
//            roles.add("normal");
//        }
        if (newUser.getId() == 1) {
            roles.add("admin");
        } else {
            roles.add("normal");
        }
        userDTO.setRoles(roles);
        return ResultVOUtils.success(userDTO);
//        return ResultVOUtils.success();
    }

    @RequestMapping(value = "/addUser")
    @ResponseBody
    public ResultVO<User> addUser(@RequestBody User user) {
        return userService.addUser(user);
    }

    @RequestMapping(value = "/editUser")
    @ResponseBody
    public ResultVO<UserDTO> editUser(@RequestBody UserDTO user) {
        return userService.editUser(user);
    }

    @RequestMapping(value = "/delUser")
    public ResultVO<User> delUser(Integer id) {
        return userService.delUser(id);
    }

    @RequestMapping(value = "/listUser")
    public ResultVO<UserDTO> listUser(UserDTO userDTO, Pageable pageable) {
        PageVO<UserDTO> list = userService.listUser(userDTO, pageable);
        return ResultVOUtils.success(list);
    }
}
